const express = require('express');
const router = express.Router();
const { Course, Category, User } = require('../../models');
const { Op } = require('sequelize');
const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');

/**
 * 公共方法：查询当前课程
 */
async function getCourse(req) {
  // 获取课程 ID
  const { id } = req.params;

  // 查询当前课程
  const course = await Course.findByPk(id, getCondition());

  // 如果没有找到，就抛出异常
  if (!course) {
    throw new NotFoundError(`ID: ${id}的课程未找到。`)
  }

  return course;
}
function getCondition() {
  return {
    attributes: { exclude: ['CategoryId', 'UserId'] },
    include: [
      {
        model: Category,
        as: 'category',
        attributes: ['id', 'name']
      },
      {
        model: User,
        as: 'user',
        attributes: ['id', 'username', 'avatar']
      }
    ]
  }
}
/**
 * 查询课程列表
 * GET /admin/articles
 */
router.get('/', async function (req, res) {
  try {
    // 定义查询条件

    const { categoryId, userId, name, recommended, introductory, page, size } = req.query;

    if (categoryId) {
      condition.where.categoryId = categoryId;
    }

    if (userId) {
      condition.where.userId = userId;
    }

    if (name) {
      condition.where.name = {
        [Op.like]: `%${name}%`
      };
    }

    if (recommended) {
      condition.where.recommended = recommended === 'true';
    }

    if (introductory) {
      condition.where.introductory = introductory === 'true'
    }

    const pageNum = page ? page : 1;
    const condition = {
      ...getCondition(),
      order: [['id', 'DESC']],
      offset: Number((pageNum - 1) * size),
      limit: Number(size)
    };
    // 查询数据
    const { count, rows } = await Course.findAndCountAll(condition);

    // 返回查询结果
    success(res, '查询课程列表成功。', {
      articles: rows,
      pagination: {
        total: count,
        page,
        size,
      }
    });
  } catch (error) {
    // 返回错误信息
    failure(res, error);
  }
});
/**
 * 查询课程详情
 */
router.get('/:id', async function (req, res) {
  try {
    const course = await getCourse(req);
    success(res, '查询课程成功。', { course });

  } catch (error) {
    failure(res, error);
  }
})
/**
 * 公共方法：白名单过滤
 * @param req
 * @returns {{image: *, name, introductory: (boolean|*), categoryId: (number|*), content, recommended: (boolean|*)}}
 */
function filterBody(req) {
  return {
    categoryId: req.body.categoryId,
    name: req.body.name,
    image: req.body.image,
    recommended: req.body.recommended,
    introductory: req.body.introductory,
    content: req.body.content
  };
}
/**
 * 创建课程
 * POST /admin/courses
 */
router.post('/', async function (req, res) {
  try {
    const body = filterBody(req);

    // 获取当前登录的用户 ID
    body.userId = req.user.id;

    const course = await Course.create(body);
    success(res, '创建课程成功。', { course }, 201);
  } catch (error) {
    failure(res, error);
  }
});
/**
 * 更新课程
 */
router.put('/:id', async function (req, res) {
  try {
    const course = await getCourse(req);
    const body = filterBody(req);
    await course.update(body)
    success(res, '更新文章成功。', { course });

  } catch (error) {
    failure(res, error);
  }
})
module.exports = router;
